package com.yqman.dbc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class ManagementConnection {
	private static String jdbcClassName;
	private static String usrName;
	private static String pwd;
	private static String url;
	private static String dataBaseName;
	private static Logger logger = Logger.getLogger(ManagementConnection.class);
	
	private static ManagementConnection instance = new ManagementConnection();
	private java.sql.Connection conn = null;
	private java.sql.Statement stmt = null;
	
	
	
	private ManagementConnection(){
		BasicConfigurator.configure();  
		Properties p = new Properties();
		try {
			p.load(new FileInputStream("src/main/jdbc.properties"));
			jdbcClassName = p.getProperty("driverClass");
			url = p.getProperty("jdbcUrl");
			dataBaseName = p.getProperty("dataBaseName");
			usrName = p.getProperty("userName");
			pwd = p.getProperty("password");
			Class.forName(jdbcClassName);
			conn = java.sql.DriverManager.getConnection(url+dataBaseName,usrName,pwd);
			stmt = conn.createStatement();
			
		} catch (FileNotFoundException e) {
			logger.error("ConnectionDriver() FileNotFoundException "+e.getMessage()); 
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("ConnectionDriver() IOException "+e.getMessage());
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			logger.error("ConnectionDriver() ClassNotFoundException "+e.getMessage());
			e.printStackTrace();
		} catch (SQLException e) {
			logger.error("ConnectionDriver() SQLException "+e.getMessage());
			e.printStackTrace();
		}
		logger.info("ConnectionDriver() sucess");
	}
	public static ManagementConnection getInstance(){
		return instance;
	}
	
	
	public boolean execute(String sql){
		boolean flag = false;
		try {
			flag = stmt.execute(sql);
			
		} catch (SQLException e) {
			logger.error("execute failed "+sql+"\n"+e.getMessage());
			e.printStackTrace();
		}
		logger.info("execute success \n"+sql);
		
		return flag;
		
	}
	
	public ResultSet executeQuery(String sql){
		ResultSet result = null;
		try {
			result = stmt.executeQuery(sql);
		} catch (SQLException e) {
			logger.error("executeQuery failed "+sql+"\n"+e.getMessage());
			e.printStackTrace();
		}
		logger.info("executeQuery success \n"+sql);
		return result;
	}
	@Override
	protected void finalize() throws Throwable {
		if(conn!=null) conn.close();
		if(stmt!=null) stmt.close();
		
		super.finalize();
	}
	
}
